﻿using OldPlatForm_backup_Migration.entity;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OldPlatForm_backup_Migration
{
    public partial class MainForm : Form
    {
        private static readonly string CONNStr = @"server={0};uid={1};pwd={2};database={3}";
        private string dtFormat = "yyyy/MM/dd";
        private List<string> ErrorTableList = new List<string>();
        private SqlSugarClient newDb;
        private SqlSugarClient oldDb;
        private List<string> paramTable = new List<string>();
        private List<string> selTable = new List<string>();
        private long SumCount = 0;
        private double SumTimes = 0;

        public MainForm()
        {
            InitializeComponent();
        }

        private void btnConn_Click(object sender, EventArgs e)
        {
            if (tbOldServerIp.Text == "")
            {
                MessageBox.Show("源服务器ip不能为空。");
                return;
            }
            if (tbOldUser.Text == "")
            {
                MessageBox.Show("源服务器用户名不能为空。");
                return;
            }
            if (tbOldPwd.Text == "")
            {
                MessageBox.Show("源服务器密码不能为空。");
                return;
            }
            if (cbbOldDB.Text == "")
            {
                MessageBox.Show("源数据库名称不能为空。");
                return;
            }
            if (tbNewServerIp.Text == "")
            {
                MessageBox.Show("目的服务器ip不能为空。");
                return;
            }
            if (tbNewUser.Text == "")
            {
                MessageBox.Show("目的服务器用户名不能为空。");
                return;
            }
            if (tbNewPwd.Text == "")
            {
                MessageBox.Show("目的服务器密码不能为空。");
                return;
            }
            if (cbbNewDB.Text == "")
            {
                MessageBox.Show("目的数据库名称不能为空。");
                return;
            }

            try
            {
                // 连接源数据库
                oldDb = new SqlSugarClient(new ConnectionConfig
                {
                    ConnectionString = string.Format(CONNStr, tbOldServerIp.Text, tbOldUser.Text, tbOldPwd.Text, cbbOldDB.Text),
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true,
                }, db =>
                {
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
                    };
                });
                newDb = new SqlSugarClient(new ConnectionConfig
                {
                    ConnectionString = string.Format(CONNStr, tbNewServerIp.Text, tbNewUser.Text, tbNewPwd.Text, cbbNewDB.Text),
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true,
                }, db =>
                {
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
                    };
                });
                if (!oldDb.Ado.IsValidConnection())
                {
                    MessageBox.Show("源数据库连接失败，请检查配置");
                    return;
                }
                if (!newDb.Ado.IsValidConnection())
                {
                    MessageBox.Show("目标数据库连接失败，请检查配置");
                    return;
                }
                MessageBox.Show("数据库连接成功。", "提示框");
                groupBox4.Enabled = true;
                panel1.Enabled = true;
                btnDisConn.Enabled = true;
                btnConn.Enabled = false;
                groupBox2.Enabled = false;
                groupBox3.Enabled = false;
            }
            catch (Exception ex)
            {
                // 抛出异常
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDataMigration_Click(object sender, EventArgs e)
        {
            if (selTable == null || selTable.Count == 0)
            {
                MessageBox.Show("请先选择需要迁移的数据");
                return;
            }

            DialogResult res = MessageBox.Show("数据迁移会删除目标数据库时间范围内的相关表的数据，\r\n确定开始迁移/同步吗？", "确认框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res != DialogResult.OK)
            {
                return;
            }

            btnParamSync.Enabled = false;
            btnDataMigration.Enabled = false;
            groupBox1.Enabled = false;
            groupBox4.Enabled = false;

            // 创建线程
            Task.Factory.StartNew(async () =>
            {
                foreach (string item in selTable)
                {
                    if (item == TableConstant.hourRpt)
                    {
                        // 迁移小时报数据
                        await MigrateDataAsync("小时报");
                    }
                    else if (item == TableConstant.shiftRpt)
                    {
                        // 迁移班报数据
                        await MigrateDataAsync("班报");
                    }
                    else if (item == TableConstant.dayRpt)
                    {
                        // 迁移日报数据
                        await MigrateDataAsync("日报");
                    }
                    else if (item == TableConstant.processData)
                    {
                        // 迁移工艺数据
                        await MigrateDataAsync("工艺");
                    }
                    else if (item == TableConstant.effectData)
                    {
                        // 迁移效应记录数据
                        await MigrateDataAsync("效应记录");
                    }
                    else if (item == TableConstant.faultData)
                    {
                        // 迁移故障记录数据
                        await MigrateDataAsync("故障记录");
                    }
                    else if (item == TableConstant.operateData)
                    {
                        // 迁移人工操作记录数据
                        await MigrateDataAsync("人工操作记录");
                    }
                    else if (item == TableConstant.paramChangeData)
                    {
                        // 迁移参数修改记录数据
                        await MigrateDataAsync("参数修改记录");
                    }
                    else if (item == TableConstant.historyData)
                    {
                        // 迁移历史数据
                        await MigrateHistoryAnsyc();
                    }
                }
                statusLabel.Text = string.Format("迁移完成，共：{0}条数据。耗时：{1}秒", SumCount, SumTimes);
                tbMemo.AppendText(statusLabel.Text + "\r\n");
            });

            btnParamSync.Enabled = true;
            btnDataMigration.Enabled = true;
            groupBox1.Enabled = true;
            groupBox4.Enabled = true;
        }

        private void btnDisConn_Click(object sender, EventArgs e)
        {
            if (oldDb != null)
            {
                oldDb.Close();
            }
            if (newDb != null)
            {
                newDb.Close();
            }
            groupBox4.Enabled = false;
            panel1.Enabled = false;
            btnConn.Enabled = true;
            btnDisConn.Enabled = false;
            groupBox2.Enabled = true;
            groupBox3.Enabled = true;
        }

        private void btnParamSync_Click(object sender, EventArgs e)
        {
            DialogResult res = MessageBox.Show("参数同步会清空目标数据库相关表的数据，\r\n确定开始参数同步吗？", "确认框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res != DialogResult.OK)
            {
                return;
            }
            btnParamSync.Enabled = false;
            btnDataMigration.Enabled = false;
            groupBox1.Enabled = false;
            groupBox4.Enabled = false;

            // 同步生产参数
            SyncParam<ProductParam>("生产", TableConstant.productParam);
            // 同步系统参数
            SyncParam<SystemParam>("系统", TableConstant.systemParam);
            // 同步地址参数
            SyncParam<AddressParam>("地址", TableConstant.addressParam);
            // 同步打壳深度参数
            SyncParam<DepthParam>("打壳深度", TableConstant.depthParam);

            btnParamSync.Enabled = true;
            btnDataMigration.Enabled = true;
            groupBox1.Enabled = true;
            groupBox4.Enabled = true;
        }

        private void cbbSelDate_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbbSelDate.SelectedIndex)
            {
                case 1:
                    dtpStart.Value = dtpEnd.Value.AddDays(-6);
                    break;

                case 2:
                    dtpStart.Value = dtpEnd.Value.AddDays(-14);
                    break;

                case 3:
                    dtpStart.Value = dtpEnd.Value.AddMonths(-1);
                    break;

                case 4:
                    dtpStart.Value = dtpEnd.Value.AddMonths(-3);
                    break;

                case 5:
                    dtpStart.Value = dtpEnd.Value.AddMonths(-6);
                    break;

                case 6:
                    dtpStart.Value = dtpEnd.Value.AddYears(-1);
                    break;

                case 7:
                    dtpStart.Value = dtpEnd.Value.AddYears(-2);
                    break;

                case 8:
                    dtpStart.Value = dtpEnd.Value.AddYears(-3);
                    break;

                default:
                    dtpStart.Value = DateTime.Today;
                    break;
            }
        }

        private void ccbDayRpt_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbDayRpt.Checked)
            {
                selTable.Add(TableConstant.dayRpt);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.dayRpt);
            }
        }

        private void ccbEffectData_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbEffectData.Checked)
            {
                selTable.Add(TableConstant.effectData);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.effectData);
            }
        }

        private void ccbFaultData_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbFaultData.Checked)
            {
                selTable.Add(TableConstant.faultData);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.faultData);
            }
        }

        private void ccbHistory_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbHistory.Checked)
            {
                selTable.Add(TableConstant.historyData);
                ccbHourRpt.Checked = false;
                ccbShiftRpt.Checked = false;
                ccbDayRpt.Checked = false;
                ccbProcessData.Checked = false;
                ccbEffectData.Checked = false;
                ccbFaultData.Checked = false;
                ccbOperateData.Checked = false;
                ccbParamChangeData.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.historyData);
            }
        }

        private void ccbHourRpt_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbHourRpt.Checked)
            {
                selTable.Add(TableConstant.hourRpt);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.hourRpt);
            }
        }

        private void ccbOperateData_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbOperateData.Checked)
            {
                selTable.Add(TableConstant.operateData);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.operateData);
            }
        }

        private void ccbParamChangeData_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbParamChangeData.Checked)
            {
                selTable.Add(TableConstant.paramChangeData);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.paramChangeData);
            }
        }

        private void ccbProcessData_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbProcessData.Checked)
            {
                selTable.Add(TableConstant.processData);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.processData);
            }
        }

        private void ccbSelectAll_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbSelectAll.Checked)
            {
                ccbHourRpt.Checked = true;
                ccbShiftRpt.Checked = true;
                ccbDayRpt.Checked = true;
                ccbProcessData.Checked = true;
                ccbEffectData.Checked = true;
                ccbFaultData.Checked = true;
                ccbOperateData.Checked = true;
                ccbParamChangeData.Checked = true;
            }
            else
            {
                ccbHourRpt.Checked = false;
                ccbShiftRpt.Checked = false;
                ccbDayRpt.Checked = false;
                ccbProcessData.Checked = false;
                ccbEffectData.Checked = false;
                ccbFaultData.Checked = false;
                ccbOperateData.Checked = false;
                ccbParamChangeData.Checked = false;
                ccbHistory.Checked = false;
            }
        }

        private void ccbShiftRpt_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbShiftRpt.Checked)
            {
                selTable.Add(TableConstant.shiftRpt);
            }
            else
            {
                selTable.Remove(TableConstant.shiftRpt);
            }
        }

        private void dtpEnd_ValueChanged(object sender, EventArgs e)
        {
            if (dtpStart.Value > dtpEnd.Value)
            {
                dtpStart.Value = dtpEnd.Value;
            }
        }

        private void dtpStart_ValueChanged(object sender, EventArgs e)
        {
            if (dtpStart.Value > dtpEnd.Value)
            {
                dtpEnd.Value = dtpStart.Value;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            groupBox4.Enabled = false;
            panel1.Enabled = false;
            btnDisConn.Enabled = false;
            statusLabel.Text = "";
            cbbSelDate.SelectedIndex = 0;
            dtpEnd.Value = DateTime.Today.AddDays(-1);
            dtpEnd.MaxDate = DateTime.Today;
            dtpStart.Value = DateTime.Today.AddDays(-1);
            dtpStart.MaxDate = DateTime.Today;
            tbOldServerIp.Text = "192.168.1.201";
            tbOldUser.Text = "sa";
            tbOldPwd.Text = "sa";
            cbbOldDB.SelectedIndex = 0;
            tbNewServerIp.Text = "192.168.1.202";
            tbNewUser.Text = "sa";
            tbNewPwd.Text = "jsjz@ckxt.4080";
            cbbNewDB.SelectedIndex = 0;
            paramTable.Clear();
            paramTable.Add(TableConstant.addressParam);
            paramTable.Add(TableConstant.depthParam);
            paramTable.Add(TableConstant.productParam);
            paramTable.Add(TableConstant.systemParam);
            this.Text = this.Text + " V" + Application.ProductVersion;
        }

        /// <summary>
        /// 数据迁移
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns></returns>
        private async Task MigrateDataAsync(string type)
        {
            try
            {
                int subCount = 0;
                double subTimes = 0;
                DateTime dt2 = dtpEnd.Value;
                DateTime dt1 = dtpStart.Value;
                if (dt1 < dt2.AddMonths(-1))
                {
                    dt1 = dt2.AddMonths(-1);
                }
                // 查询数据
                if (type == "小时报")
                {
                    do
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<HourRpt>()
                        .Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            break;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始迁移{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        newDb.Ado.BeginTran();
                        // 删除原数据
                        newDb.Deleteable<HourRpt>().Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ExecuteCommand();
                        // 插入新数据
                        int count = (list.Count < 2000) ?
                            newDb.Insertable(list).PageSize(200).ExecuteCommand() :
                            newDb.Fastest<HourRpt>().PageSize(2000).BulkCopy(list);
                        // 提交事务
                        newDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        subTimes += seconds;
                        subCount += count;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}--{1}的{2}数据迁移完成，迁移{3}条。耗时：{4}秒", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        dt2 = dt1.AddDays(-1);
                        dt1 = dt2.AddMonths(-1);
                        if (dt1 < dtpStart.Value)
                        {
                            dt1 = dtpStart.Value;
                        }
                    } while (dt1 < dt2);
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            statusLabel.Text = string.Format("{0}数据迁移完成，累计{1}条数据。耗时：{2}秒", type, subCount, subTimes);
                            tbMemo.AppendText(statusLabel.Text + "\r\n");
                        }));
                    }
                    SumCount += subCount;
                    SumTimes += subTimes;
                }
                else if (type == "班报")
                {
                    do
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<ShiftRpt>()
                        .Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            break;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始迁移{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        newDb.Ado.BeginTran();
                        // 删除原数据
                        newDb.Deleteable<ShiftRpt>().Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ExecuteCommand();
                        // 插入新数据
                        int count = (list.Count < 2000) ?
                            newDb.Insertable(list).PageSize(200).ExecuteCommand() :
                            newDb.Fastest<ShiftRpt>().PageSize(2000).BulkCopy(list);
                        // 提交事务
                        newDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        subTimes += seconds;
                        subCount += count;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}--{1}的{2}数据迁移完成，迁移{3}条。耗时：{4}秒", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        dt2 = dt1.AddDays(-1);
                        dt1 = dt2.AddMonths(-1);
                        if (dt1 < dtpStart.Value)
                        {
                            dt1 = dtpStart.Value;
                        }
                    } while (dt1 < dt2);
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            statusLabel.Text = string.Format("{0}数据迁移完成，累计{1}条数据。耗时：{2}秒", type, subCount, subTimes);
                            tbMemo.AppendText(statusLabel.Text + "\r\n");
                        }));
                    }
                    SumCount += subCount;
                    SumTimes += subTimes;
                }
                else if (type == "日报")
                {
                    do
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<DayRpt>()
                        .Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            break;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始迁移{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        newDb.Ado.BeginTran();
                        // 删除原数据
                        newDb.Deleteable<DayRpt>().Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ExecuteCommand();
                        // 插入新数据
                        int count = (list.Count < 2000) ?
                            newDb.Insertable(list).PageSize(200).ExecuteCommand() :
                            newDb.Fastest<DayRpt>().PageSize(2000).BulkCopy(list);
                        // 提交事务
                        newDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        subTimes += seconds;
                        subCount += count;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}--{1}的{2}数据迁移完成，迁移{3}条。耗时：{4}秒", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        dt2 = dt1.AddDays(-1);
                        dt1 = dt2.AddMonths(-1);
                        if (dt1 < dtpStart.Value)
                        {
                            dt1 = dtpStart.Value;
                        }
                    } while (dt1 < dt2);
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            statusLabel.Text = string.Format("{0}数据迁移完成，累计{1}条数据。耗时：{2}秒", type, subCount, subTimes);
                            tbMemo.AppendText(statusLabel.Text + "\r\n");
                        }));
                    }
                    SumCount += subCount;
                    SumTimes += subTimes;
                }
                else if (type == "工艺")
                {
                    do
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<ProcessData>()
                        .Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            break;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始迁移{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        newDb.Ado.BeginTran();
                        // 删除原数据
                        newDb.Deleteable<ProcessData>().Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ExecuteCommand();
                        // 插入新数据
                        int count = (list.Count < 2000) ?
                            newDb.Insertable(list).PageSize(200).ExecuteCommand() :
                            newDb.Fastest<ProcessData>().PageSize(2000).BulkCopy(list);
                        // 提交事务
                        newDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        subTimes += seconds;
                        subCount += count;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}--{1}的{2}数据迁移完成，迁移{3}条。耗时：{4}秒", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        dt2 = dt1;
                        dt1 = dt2.AddMonths(-1);
                        if (dt1 < dtpStart.Value)
                        {
                            dt1 = dtpStart.Value;
                        }
                    } while (dt1 < dt2);
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            statusLabel.Text = string.Format("{0}数据迁移完成，累计{1}条数据。耗时：{2}秒", type, subCount, subTimes);
                            tbMemo.AppendText(statusLabel.Text + "\r\n");
                        }));
                    }
                    SumCount += subCount;
                    SumTimes += subTimes;
                }
                else if (type == "效应记录")
                {
                    do
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<EffectData>()
                        .Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            break;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始迁移{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        newDb.Ado.BeginTran();
                        // 删除原数据
                        newDb.Deleteable<EffectData>().Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ExecuteCommand();
                        // 插入新数据
                        int count = (list.Count < 2000) ?
                            newDb.Insertable(list).PageSize(200).ExecuteCommand() :
                            newDb.Fastest<EffectData>().PageSize(2000).BulkCopy(list);
                        // 提交事务
                        newDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        subTimes += seconds;
                        subCount += count;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}--{1}的{2}数据迁移完成，迁移{3}条。耗时：{4}秒", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        dt2 = dt1.AddDays(-1);
                        dt1 = dt2.AddMonths(-1);
                        if (dt1 < dtpStart.Value)
                        {
                            dt1 = dtpStart.Value;
                        }
                    } while (dt1 < dt2);
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            statusLabel.Text = string.Format("{0}数据迁移完成，累计{1}条数据。耗时：{2}秒", type, subCount, subTimes);
                            tbMemo.AppendText(statusLabel.Text + "\r\n");
                        }));
                    }
                    SumCount += subCount;
                    SumTimes += subTimes;
                }
                else if (type == "故障记录")
                {
                    do
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<FaultData>()
                        .Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            break;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始迁移{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        newDb.Ado.BeginTran();
                        // 删除原数据
                        newDb.Deleteable<FaultData>().Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ExecuteCommand();
                        // 插入新数据
                        int count = (list.Count < 2000) ?
                            newDb.Insertable(list).PageSize(200).ExecuteCommand() :
                            newDb.Fastest<FaultData>().PageSize(2000).BulkCopy(list);
                        // 提交事务
                        newDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        subTimes += seconds;
                        subCount += count;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}--{1}的{2}数据迁移完成，当次{3}条。耗时：{4}秒", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        dt2 = dt1.AddDays(-1);
                        dt1 = dt2.AddMonths(-1);
                        if (dt1 < dtpStart.Value)
                        {
                            dt1 = dtpStart.Value;
                        }
                    } while (dt1 < dt2);
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            statusLabel.Text = string.Format("{0}数据迁移完成，累计{1}条数据。耗时：{2}秒", type, subCount, subTimes);
                            tbMemo.AppendText(statusLabel.Text + "\r\n");
                        }));
                    }
                    SumCount += subCount;
                    SumTimes += subTimes;
                }
                else if (type == "人工操作记录")
                {
                    do
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<OperateData>()
                        .Where(it => SqlFunc.Between(it.Operate_date, dt1, dt2)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            break;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始迁移{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        newDb.Ado.BeginTran();
                        // 删除原数据
                        newDb.Deleteable<OperateData>().Where(it => SqlFunc.Between(it.Operate_date, dt1, dt2)).ExecuteCommand();
                        // 插入新数据
                        int count = (list.Count < 2000) ?
                            newDb.Insertable(list).PageSize(200).ExecuteCommand() :
                            newDb.Fastest<OperateData>().PageSize(2000).BulkCopy(list);
                        // 提交事务
                        newDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        subTimes += seconds;
                        subCount += count;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}--{1}的{2}数据迁移完成，当次{3}条。耗时{4}秒", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        dt2 = dt1.AddDays(-1);
                        dt1 = dt2.AddMonths(-1);
                        if (dt1 < dtpStart.Value)
                        {
                            dt1 = dtpStart.Value;
                        }
                    } while (dt1 < dt2);
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            statusLabel.Text = string.Format("{0}数据迁移完成，累计{1}条数据。耗时{2}秒", type, subCount, subTimes);
                            tbMemo.AppendText(statusLabel.Text + "\r\n");
                        }));
                    }
                    SumCount += subCount;
                    SumTimes += subTimes;
                }
                else if (type == "参数修改记录")
                {
                    do
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<ParamChangeData>()
                        .Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            break;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始迁移{0}--{1}的{2}数据...", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        newDb.Ado.BeginTran();
                        // 删除原数据
                        newDb.Deleteable<ParamChangeData>().Where(it => SqlFunc.Between(it.Record_date, dt1, dt2)).ExecuteCommand();
                        // 插入新数据
                        int count = (list.Count < 2000) ?
                            newDb.Insertable(list).PageSize(200).ExecuteCommand() :
                            newDb.Fastest<ParamChangeData>().PageSize(2000).BulkCopy(list);
                        // 提交事务
                        newDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        subTimes += seconds;
                        subCount += count;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}--{1}的{2}数据迁移完成，当次{3}条。耗时：{4}秒", dt1.ToString(dtFormat), dt2.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        dt2 = dt1.AddDays(-1);
                        dt1 = dt2.AddMonths(-1);
                        if (dt1 < dtpStart.Value)
                        {
                            dt1 = dtpStart.Value;
                        }
                    } while (dt1 < dt2);
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            statusLabel.Text = string.Format("{0}数据迁移完成，累计{1}条数据。耗时：{2}秒", type, subCount, subTimes);
                            tbMemo.AppendText(statusLabel.Text + "\r\n");
                        }));
                    }
                    SumCount += subCount;
                    SumTimes += subTimes;
                }
            }
            catch (Exception ex)
            {
                if (InvokeRequired)
                {
                    Invoke(new Action(() =>
                    {
                        statusLabel.Text = string.Format("{0}数据迁移失败，正在回滚...", type);
                        tbMemo.AppendText(string.Format("{0}数据迁移失败，原因：{1}\r\n", type, ex.Message));
                    }));
                }
                // 回滚事务
                newDb.Ado.RollbackTran();
            }
        }

        /// <summary>
        /// 迁移历史数据
        /// </summary>
        /// <returns></returns>
        private async Task MigrateHistoryAnsyc()
        {
            // 遍历日期查询表名
            DateTime dt2 = dtpEnd.Value;
            DateTime dt1 = dtpStart.Value;
            do
            {
                if (InvokeRequired)
                {
                    Invoke(new Action(() =>
                    {
                        statusLabel.Text = string.Format("查询{0}的历史数据表。", dt2.ToString(dtFormat));
                        tbMemo.AppendText(statusLabel.Text + "\r\n");
                    }));
                }
                string slotId = tb_slotId.Text.Trim();
                string dtFmt = dt2.ToString("yyyyMMdd");
                string sql = slotId == "" ? string.Format(@"select name from sys.tables where name like '%{0}'", dtFmt)
                    : string.Format(@"select name from sys.tables where name = 'his_{0}{1}'", slotId, dtFmt);
                List<string> tbList = await oldDb.SqlQueryable<DbTableInfo>(sql).Select(it => it.Name).ToListAsync();
                dt2 = dt2.AddDays(-1);
                if (tbList == null || tbList.Count == 0)
                {
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            statusLabel.Text = "没有历史数据表。";
                            tbMemo.AppendText(statusLabel.Text + "\r\n");
                        }));
                    }
                    continue;
                }
                // 遍历表
                foreach (string tb in tbList)
                {
                    try
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = "开始历史数据表[" + tb + "]的数据迁移...";
                                tbMemo.AppendText("查询" + tb + "的历史数据...\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        // 查询历史数据
                        List<HistoryData> list = await oldDb.Queryable<HistoryData>().AS(tb).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("历史数据表[{0}]没有数据...\r\n", tb));
                                }));
                            }
                            continue;
                        }
                        // 判断目标数据表是否存在
                        bool tbExist = newDb.DbMaintenance.IsAnyTable(tb);
                        // 开启事务
                        newDb.Ado.BeginTran();
                        if (tbExist)
                        {
                            // 如果表存在，清空数据表
                            newDb.DbMaintenance.TruncateTable(tb);
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    statusLabel.Text = string.Format("清空历史数据表[{0}]。", tb);
                                    tbMemo.AppendText(statusLabel.Text + "\r\n");
                                }));
                            }
                        }
                        else
                        {
                            // 如果表不存在，创建表
                            newDb.CodeFirst.As<HistoryData>(tb).InitTables<HistoryData>();
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    statusLabel.Text = string.Format("创建历史数据表[{0}]。", tb);
                                    tbMemo.AppendText(statusLabel.Text + "\r\n");
                                }));
                            }
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                tbMemo.AppendText("开始历史数据表[" + tb + "]的数据迁移...\r\n");
                            }));
                        }
                        // 将数据插入到目标数据库
                        int count = newDb.Fastest<HistoryData>().AS(tb).PageSize(2000).BulkCopyAsync(list).Result;
                        // 提交事务
                        newDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        SumTimes += seconds;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("[{0}]的历史数据迁移完成，共：{1}条数据。耗时：{2}秒", tb, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        SumCount += count;
                    }
                    catch (Exception ex)
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("[{0}]的历史数据迁移失败，正在回滚...", tb);
                                tbMemo.AppendText(string.Format("[{0}]的历史数据迁移失败，原因：{1}\r\n", tb, ex.Message));
                            }));
                        }
                        // 回滚事务
                        newDb.Ado.RollbackTran();
                        ErrorTableList.Add(tb);
                        continue;
                    }
                }
            } while (dt1 <= dt2);
        }

        /// <summary>
        /// 数据同步
        /// </summary>
        /// <typeparam name="T">数据表实体类</typeparam>
        /// <param name="type">类型</param>
        /// <param name="tbName">表名</param>
        /// <returns></returns>
        private void SyncParam<T>(string type, string tbName) where T : class, new()
        {
            try
            {
                statusLabel.Text = string.Format("正在同步{0}参数...", type);
                tbMemo.AppendText(string.Format("查询{0}参数...\r\n", type));
                var list = oldDb.Queryable<T>().ToList();
                tbMemo.AppendText(string.Format("同步{0}参数...\r\n", type));
                // 开启事务
                newDb.Ado.BeginTran();
                // 清空数据
                newDb.DbMaintenance.TruncateTable(tbName);
                int count = newDb.Insertable(list).PageSize(200).ExecuteCommand();
                // 提交事务
                newDb.Ado.CommitTran();
                statusLabel.Text = string.Format("{0}参数同步成功，共：{1}条数据。", type, count);
                tbMemo.AppendText(string.Format("{0}参数同步成功，共：{1}条数据。\r\n", type, count));
            }
            catch (Exception ex)
            {
                statusLabel.Text = string.Format("{0}参数同步失败，正在回滚...", type);
                tbMemo.AppendText(string.Format("{0}参数同步失败。原因：{1}\r\n", type, ex.Message));
                // 回滚事务
                newDb.Ado.RollbackTran();
            }
        }

        private void tbMemo_TextChanged(object sender, EventArgs e)
        {
            if (tbMemo.Lines.Length > 1000)
            {
                tbMemo.Lines[0] = "";
            }
        }
    }
}